package com.cardbaobao.cardbabyclient.utils;

import android.content.Context;
import android.text.TextUtils;


import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.cardbaobao.cardbabyclient.api.Api;
import com.cardbaobao.cardbabyclient.callback.ICityInfoCallback;
import com.cardbaobao.cardbabyclient.callback.OnLocationListener;
import com.cardbaobao.cardbabyclient.model.City;
import com.cardbaobao.cardbabyclient.model.LatLng;
import com.cardbaobao.cardbabyclient.model.MyLocation;

import rx.Observable;
import rx.Subscriber;

/**
 * Created by zad on 2016/12/25 0025.
 * 定位工具类
 */
public class LocationUtil {
    /**默认广州经度*/
    private static final double DEFAULT_LONGITUDE = 113.2759952545166;
    /** 默认广州纬度*/
    private static final double DEFAULT_LATITUDE = 23.117055306224895;
    /**默认广东省ID*/
    private static final String DEFAULT_PROVINCE_ID = "100";
    /**默认城市*/
    private static final String DEFAULT_CITY = "广州市";//广州市
    /**默认城市ID*/
    private static final String DEFAULT_CITY_ID = "373";//373

    /**定位监听类*/
    private static MyBDLocationListener mListener;
    /**定位成功Code*/
    public final static int LOCATION_SUCCESS_CODE = 0x200;
    /**定位失败Code*/
    public final static int LOCATION_FAILURE_CODE=0x201;


    private static AMapLocationClient mLocationClient;
    /**定位回调监听器*/
    private static AMapLocationListener mLocationListener =new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation aMapLocation) {
            if(mListener!=null){
                mListener.onLocationChanged(aMapLocation);
            }
        }
    };

    /**
     * 开始定位
     * @param context context
     * @param locationListener 定位回调接口
     */
    public static void startLocation(Context context, OnLocationListener locationListener) {
        if (mListener == null) {
            mListener = new MyBDLocationListener(locationListener);
        } else {
            mListener.setOnLocationListener(locationListener);
        }
        if(mLocationClient==null){
            mLocationClient=new AMapLocationClient(context.getApplicationContext());
        }
        mLocationClient.setLocationListener(mLocationListener);
        AMapLocationClientOption locationOption=new AMapLocationClientOption();
        locationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        locationOption.setOnceLocation(true);
        locationOption.setOnceLocationLatest(true);
        mLocationClient.setLocationOption(locationOption);
        mLocationClient.startLocation();
    }

    /**
     * 停止定位
     */
    public static void stopLocation() {
        if(mListener!=null&&mLocationClient!=null){
            mLocationClient.stopLocation();
            mLocationClient.onDestroy();
            mLocationClient.unRegisterLocationListener(mLocationListener);
            mLocationClient=null;
        }
    }

    /**
     * 定位结果监听回调类，重写onReceiveLocation方法
     */
    private static class MyBDLocationListener implements AMapLocationListener {
        /**
         * 定位结果回调监听
         */
        private OnLocationListener locationListener;

        private void setOnLocationListener(OnLocationListener locationListener) {
            this.locationListener = locationListener;
        }

        private MyBDLocationListener(OnLocationListener locationListener) {
            this.locationListener = locationListener;
        }

        @Override
        public void onLocationChanged(AMapLocation aMapLocation) {
            if(aMapLocation!=null){
                int errorCode=aMapLocation.getErrorCode();//错误码
                if(errorCode==AMapLocation.LOCATION_SUCCESS){
                    //定位成功
                    String cityName=aMapLocation.getCity();//城市
                    SharedPreferencesUtil.LocationInfo.setCityName(cityName);
                    SharedPreferencesUtil.LocationInfo.setCityLatitude(String.valueOf(aMapLocation.getLatitude()));
                    SharedPreferencesUtil.LocationInfo.setCityLongitude(String.valueOf(aMapLocation.getLongitude()));
                    set24FirstLocationTime();
                    LatLng latLng=new LatLng(aMapLocation.getLatitude(),aMapLocation.getLongitude());
                    if(locationListener!=null){
                        MyLocation location=new MyLocation(cityName,latLng);
                        locationListener.locationResult(location,LOCATION_SUCCESS_CODE);
                    }
                }else{
                    //失败
                    if (locationListener != null) {
                        locationListener.locationResult(null,LOCATION_FAILURE_CODE);
                    }
                }
            }else{
                if(locationListener!=null){
                    locationListener.locationResult(null,LOCATION_FAILURE_CODE);
                }
            }
            stopLocation();
        }
    }

    /**
     * 根据城市名获取省ID和城市ID
     *
     * @param cityName 城市名
     */
    public static void getProvinceCityIDByCityName(final ICityInfoCallback cityInfoResponse,
                                                   final String cityName) {
        //根据城市名请求城市ID,省ID
        Observable<String> observable=Api.queryCityInfo(cityName);
        observable.subscribe(new Subscriber<String>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                cityInfoResponse.onCityInfoResponse(null);
            }

            @Override
            public void onNext(String s) {
                City city = JsonUtil.getData(s,City.class);
                cityInfoResponse.onCityInfoResponse(city);
            }
        });
    }
    /**
     * 获取当前省份ID
     */
    public static String getProvinceID() {
        String provinceID = SharedPreferencesUtil.LocationInfo.getProvinceId();
        if (TextUtils.isEmpty(provinceID)) {
            provinceID = DEFAULT_PROVINCE_ID;
        }
        return provinceID;
    }

    /**
     * 保存当前省份ID
     */
    public static void setProvinceID( String provinceID) {
        if(!TextUtils.isEmpty(provinceID)){
            SharedPreferencesUtil.LocationInfo.setProvinceId(provinceID);
        }
    }

    /**
     * 获取当前城市
     */
    public static String getCityName() {
        String city = SharedPreferencesUtil.LocationInfo.getCityName();
        if (TextUtils.isEmpty(city)) {
            city = DEFAULT_CITY;
        }
        return city;
    }

    /**
     * 保存当前城市
     */
    public static void setCityName(String cityName) {
        if(!TextUtils.isEmpty(cityName)){
            SharedPreferencesUtil.LocationInfo.setCityName(cityName);
        }
    }

    /**
     * 获取当前城市
     */
    public static String getCityID() {
        String cityID = SharedPreferencesUtil.LocationInfo.getCityId();
        if (TextUtils.isEmpty(cityID)) {
            cityID = DEFAULT_CITY_ID;
        }
        return cityID;
    }

    /**
     * 保存当前城市ID
     */
    public static void setCityID(String cityID) {
        if(!TextUtils.isEmpty(cityID)){
            SharedPreferencesUtil.LocationInfo.setCityId(cityID);
        }
    }

    /**
     * 获取当前城市经纬度
     */
    public static LatLng getCityLatLng() {
        LatLng latLng = null;
        String city_latitude = SharedPreferencesUtil.LocationInfo.getCityLatitude();
        String city_longitude = SharedPreferencesUtil.LocationInfo.getCityLongitude();
        if (!TextUtils.isEmpty(city_longitude) && !TextUtils.isEmpty(city_latitude)) {
            try {
                double latitude = Double.parseDouble(city_latitude);//纬度
                double longitude = Double.parseDouble(city_longitude);//经度
                latLng = new LatLng(latitude, longitude);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {//默认经纬度
            latLng = new LatLng(DEFAULT_LATITUDE, DEFAULT_LONGITUDE);
        }
        return latLng;
    }

    /**
     * 保存当前城市经纬度
     */
    public static void setCityLatLng(LatLng latLng) {
        if (latLng != null) {
            SharedPreferencesUtil.LocationInfo.setCityLatitude(String.valueOf(latLng.latitude));
            SharedPreferencesUtil.LocationInfo.setCityLongitude(String.valueOf(latLng.longitude));
        }
    }

    /**
     * 设置24小时内第一次定位时间
     */
    public static void set24FirstLocationTime(){
        SharedPreferencesUtil.LocationInfo.set24FirstLocation(System.currentTimeMillis());
    }

    /**
     *上次定位是否是24小时内
     */
    public static boolean is24FirstLocation(){
        boolean is24First = false;
        long currentTime = System.currentTimeMillis();//当前时间
        long lastTime = SharedPreferencesUtil.LocationInfo.get24FirstLocation();//上一次定位时间
        long diffTime = (currentTime - lastTime) / 1000 / 60 / 60;
            if(diffTime >= 24){
            //是否是24小时内第一次定位
            is24First = true;
        }
        return is24First;
    }
}
